import { computed, makeAutoObservable, configure, runInAction, action } from "mobx";

configure({ enforceActions: "observed" });

class AppleStore {
  constructor() {
    makeAutoObservable(this);
  }
  apples = [];
  isPicking = false;
  appleId = 0;
  @computed get eatApples() {
    const eatApples = this.apples.filter((apple) => apple.isEaten);
    return eatApples;
  }
  @computed get noEatApples() {
    const noEatApples = this.apples.filter((apple) => !apple.isEaten);
    return noEatApples;
  }
  @computed get eatApplesWeight() {
    const weight = this.eatApples.reduce((a, b) => {
      return (a += b.weight);
    }, 0);
    return weight;
  }
  @computed get noEatApplesWeight() {
    const weight = this.noEatApples.reduce((a, b) => {
      return (a += b.weight);
    }, 0);
    return weight;
  }
  @computed get eatApplesCount() {
    return this.eatApples.length;
  }
  @computed get noEatApplesCount() {
    return this.noEatApples.length;
  }

  @action pickApple = () => {
    if (this.isPicking) return;
    this.isPicking = true;
    new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve();
      }, 1000);
    }).then(() => {
      runInAction(() => {
        this.isPicking = false;
        this.apples.push({
          id: this.appleId++,
          weight: parseInt(300 + Math.random() * 50),
          isEaten: false,
        });
      });
    });
  };
  @action eatApple = (appleId) => {
    this.apples.find(apple => apple.id === appleId).isEaten = true
  }
}

const apple = new AppleStore();

export default apple;
